package com.lzq.springblog.controller;


import com.lzq.springblog.common.Result;
import com.lzq.springblog.common.ResultCode;
import com.lzq.springblog.model.CommentInfo;
import com.lzq.springblog.model.UserInfo;
import com.lzq.springblog.service.CommentService;
import com.lzq.springblog.service.UserService;
import com.lzq.springblog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Data
@Slf4j
@RequestMapping("/comment")
@RestController
public class CommentController {
    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/getCommentList")
    public Result getCommentList(Integer blogId, HttpServletRequest request) {
        log.info("开始执行getCommentList方法,接收博客id:{}",blogId);
        List<CommentInfo> commentInfoList = commentService.getCommentList(blogId);
        log.info("查询到评论列表:{}",commentInfoList);
        return Result.success(commentInfoList);
    }

    @PostMapping("/addComment")
    public Result addComment(Integer blogId, String content,HttpServletRequest request) {
        log.info("开始执行addComment方法,接收博客id:{}",blogId);
        //获取用户id
        String jwt = request.getHeader("user_token");
        Integer userId = (Integer) JwtUtils.getUserIdFromToken(jwt).getData();
        if (userId==null || userId<1) {
            log.error("查询的用户信息不存在");
            return Result.failed(ResultCode.FAILED);
        }
        //获取用户名称
        UserInfo userInfo = userService.getUserInfoById(userId);
        String userName = userInfo.getUserName();
        //判断能否评论
        Boolean canComment = commentService.getCanComment(userId,blogId);
        if (!canComment) {
            log.info("用户:{}对id为{}的博客评论已达上限",userName,blogId);
            return Result.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //新增评论
        CommentInfo commentInfo = new CommentInfo();
        commentInfo.setCommenterId(userId);
        commentInfo.setCommenterName(userName);
        commentInfo.setCommentedBlogId(blogId);
        commentInfo.setContent(content);
        Integer result = commentService.addComment(commentInfo);
        if (result<1) {
            log.error("新增评论失败");
            return Result.failed(ResultCode.FAILED);
        }
        return Result.success(true);
    }

}
